/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.daydream.wrapper.commons.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.io.SerializedString;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.UnwrappingBeanPropertyWriter;
import com.fasterxml.jackson.databind.util.NameTransformer;

/**
 * @author william
 * @since 2023/12/31
 */

public class CommonsWrapperUnwrappingBeanPropertyWriter extends UnwrappingBeanPropertyWriter {


    private static final long serialVersionUID = -1504287488410823215L;

    protected final Object _empty;

    public CommonsWrapperUnwrappingBeanPropertyWriter(BeanPropertyWriter base,
                                                      NameTransformer transformer, Object empty) {
        super(base, transformer);
        _empty = empty;
    }

    protected CommonsWrapperUnwrappingBeanPropertyWriter(CommonsWrapperUnwrappingBeanPropertyWriter base,
                                                         NameTransformer transformer, SerializedString name) {
        super(base, transformer, name);
        _empty = base._empty;
    }

    @Override
    protected UnwrappingBeanPropertyWriter _new(NameTransformer transformer, SerializedString newName) {
        return new CommonsWrapperUnwrappingBeanPropertyWriter(this, transformer, newName);
    }

    @Override
    public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
        if (_nullSerializer == null) {
            Object value = get(bean);
            if (value == null || value.equals(_empty)) {
                return;
            }
        }
        super.serializeAsField(bean, gen, prov);
    }
}
